<template>
    <div class="projectSelectPopup bg-white dark:bg-[var(--bg-2)]" v-loading="isLoading">
        <el-row class="h-full">
            <el-col :span="24" class="h-full">
                <div class="h-full ">
                    <treeList ref="treeListRef" v-model:inputModel="inputText" :inputProops="inputProops"
                        :inputEvents="inputEvents" :treeProops="treeProops" :treeEvents="treeEvents">
                        <template #input>
                            <div class="tree-input">
                                <el-input v-model.trim="inputText" v-bind="inputProops" v-on="inputEvents" />
                            </div>
                        </template>
                        <template #page>
                            <div
                                class="p-[16px] h-[48px] border-t border-solid border-[var(--el-border-color-lighter)]">
                                <el-checkbox class="!h-[16px]" v-model="showProjectType" label="数据包含下级单位"
                                    :true-value="UNIT_TYPE_VIEW_Map.include" :false-value="UNIT_TYPE_VIEW_Map.current"
                                    @change="viewsChange" />
                            </div>
                        </template>
                    </treeList>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script setup lang="ts">
import treeList from '@/components/treeList/treeList.vue'
import { getUnitTree } from '@/api/manage/units-manager/units-manager/index'
import { usePageVariablesStoreHook } from '@/store/modules/pageVariables'
import { UNIT_TYPE_VIEW_Map_LIST, UNIT_TYPE_VIEW_Map } from '@/constant/index'
import { cloneDeep, storageLocal } from "@pureadmin/utils";
import { usePageReloadStoreHook } from "@/store/modules/pageReload";
import router, { resetRouter } from '@/router';
import { getUserRole } from '@/api/user';
import { setUserKey, userKey } from '@/utils/auth';
import { message } from '@/utils/message';
import { closePopover } from '@/components/customPopover';
const usePageVariablesStore = usePageVariablesStoreHook()
const manageInfo = ref(usePageVariablesStore.getManage())
const isLoading = ref(false)
const treeRef = ref()
const treeListRef = ref()
const checkedUnitId = ref(null)
const showProjectType = ref(UNIT_TYPE_VIEW_Map.current)
const props = {
    label: 'unityName',
    value: 'id',
    children: 'childs',
    isLeaf: 'isLeaf',
}
const inputText = ref('')
const unityList = ref([])
const unitPathMap = ref({})

onMounted(() => {
    loadUnitTree()
    checkedUnitId.value = manageInfo.value.unityId
    showProjectType.value = manageInfo.value.views
    treeRef.value = treeListRef.value.getTreeRef()
    treeRef.value.setCurrentKey(manageInfo.value.unityId)

})
const loadUnitTree = () => {
    isLoading.value = true
    getUnitTree().then(res => {
        unityList.value = res.result.data
        initPath()
        treeRef.value.setExpandedKeys(unitPathMap.value[manageInfo.value.unityId])
    }).finally(() => {
        isLoading.value = false
    })
}
const initPath = (list = unityList.value, path = []) => {
    list.forEach(item => {
        unitPathMap.value[item.id] = path
        let copyPath = cloneDeep(path)
        copyPath.push(item.id)
        if (item.childs && item.childs.length > 0) {
            initPath(item.childs, copyPath)
        }
    })
}
const handleNodeClick = (data) => {
    let copyMange = cloneDeep(usePageVariablesStore.getManage())
    usePageVariablesStore.setManage({
        unityId: data.id,
        unityName: data.unityName,
        views: showProjectType.value
    })
    getUserRole().then(res1 => {
        checkedUnitId.value = data.id
        let userInfo = storageLocal().getItem(userKey).userInfo
        if (userInfo.roles) {
            userInfo.roles.manage = res1.result.data
        } else {
            userInfo.roles = {
                manage: res1.result.data
            }
        }
        setUserKey(userInfo.nickname, res1.result.data, userInfo);
        // window.location.reload()
        resetRouter(router.currentRoute.value)
        usePageReloadStoreHook().reloadPages()
        closePopover()
    }).catch(() => {
        usePageVariablesStore.setManage(copyMange)
        message('获取权限失败', { type: 'error' })
    })
}
const inputChange = (val) => {
    // console.log('aaaaaasdsaddasdadaaaa', val);
    treeRef.value.filter(val)
}
const filterNode = (value, data) => {
    // console.log(data);
    if (!value) return true
    return data.unityName.includes(value)
}
const viewsChange = () => {
    let info = cloneDeep(usePageVariablesStore.getManage());
    info.views = showProjectType.value;
    usePageVariablesStore.setManage(info);
    usePageReloadStoreHook().reloadPages()
};

const treeProops = ref({
    props: props,
    // load: loadNode,
    // lazy: true,
    itemSize: '46',
    data: unityList,
    checkStrictly: true,
    highlightCurrent: false,
    expandOnClickNode: false,
    nodeKey: "id",
    'filter-method': filterNode
})
const treeEvents = {
    nodeClick: handleNodeClick,
}
const inputProops = {
    placeholder: '请输入单位名称',
}
const inputEvents = {
    change: inputChange,
}
function getRef() {
    return treeRef.value
}

defineExpose({
    getRef
})
</script>
<style lang="scss" scoped>
.projectSelectPopup {
    position: relative;
    height: 100%;
    width: 304px;

    ::v-deep(.el-tree-node__content) {
        .el-tree-node__expand-icon {
            padding: 16px;
        }

        .el-checkbox {
            margin-left: -6px;
        }
    }

    .treeList1 {
        ::v-deep(.el-tree-node__content) {
            padding-left: 16px !important;

            .el-tree-node__expand-icon {
                display: none;
            }
        }

        ::v-deep(.tree-page) {
            padding: 16px;
            // display: flex;
            // justify-content: center;
        }
    }

    .tree-input {
        margin: 16px;
    }

}
</style>